package com.king.notifier;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Collections;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SmsNotifierImpl extends AbstractBufferedNotifier implements Notifier {

    private static final String SMS_NOTIFY_URL = "http://sms.notify.d.xiaonei.com:2000/receiver";

    private List<String> mobiles = Collections.emptyList();

    @Override
    public void doNotify(String msg) {
        for (String mobile : mobiles) {
            mobile = StringUtils.trimToEmpty(mobile);
            if (mobile.length() != 11 || !StringUtils.isNumeric(mobile)) {
                return;
            }
//            try {
//                msg = URLEncoder.encode(msg, "utf-8");
//            } catch (UnsupportedEncodingException e) {
//
//            }

            String param = "number=" + mobile + "&message=" + msg;
            log.info("start sending notify msg [" + msg + "]");
            BufferedReader in = null;
            try {
                URL url = new URL(SMS_NOTIFY_URL + "?" + param);
                URLConnection conn = url.openConnection();
                // 设置通用的请求属性
                conn.setRequestProperty("accept", "*/*");
                conn.setRequestProperty("connection", "Keep-Alive");
                conn.setRequestProperty("user-agent", "nuomi-report/urlConnection");
                conn.setReadTimeout(1000 * 1);
                conn.setConnectTimeout(1000 * 2);
                in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String line = in.readLine();
                log.debug("send sms notify return:" + line);
            } catch (MalformedURLException e) {
                log.error("send sms notify exception:", e);
            } catch (IOException e) {
                log.error("send sms notify exception:", e);
            } finally {
                IOUtils.closeQuietly(in);
            }
        }

    }

    public void setMobiles(List<String> mobiles) {
        this.mobiles = mobiles;
    }

}
